﻿using HXH.Serialization.Abstractions;
using ProtoBuf;
using System;
using System.IO;
using System.Threading.Tasks;

namespace HXH.Serialization.Protobuf
{
    /// <summary>
    /// Protobuf序列化
    /// </summary>
    public class ProtobufMessageSerializer : IMessageSerializer
    {
        /// <summary>
        /// 序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="message"></param>
        /// <returns></returns>
        public byte[] SerializerBytes<T>(T message)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                Serializer.Serialize<T>(ms, message);
                return ms.ToArray();
            }
        }
        /// <summary>
        /// 异步序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="message"></param>
        /// <returns></returns>
        public Task<byte[]> SerializerBytesAsync<T>(T message)
        {
            return Task.Run(() =>
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    Serializer.Serialize<T>(ms, message);
                    return ms.ToArray();
                }
            });
        }
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public T Deserialize<T>(byte[] bytes)
        {
            using (MemoryStream ms = new MemoryStream(bytes))
            {
                T t = Serializer.Deserialize<T>(ms);
                return t;
            }
        }
        /// <summary>
        /// 异步反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public Task<T> DeserializeAsync<T>(byte[] bytes)
        {
            return Task.Run(() =>
            {
                using (MemoryStream ms = new MemoryStream(bytes))
                {
                    T t = Serializer.Deserialize<T>(ms);
                    return t;
                }
            });
        }

    }
}
